package handler

import (
	"encoding/json"
	"fmt"
	"game-server/utils"
	"log"
	"net/http"
	"sync"

	pb "proto" // 替换成你的proto包路径

	"github.com/gorilla/websocket"
)

var upgrader = websocket.Upgrader{
	CheckOrigin: func(r *http.Request) bool {
		return true // 在生产环境中需要proper的origin检查
	},
}

type Connection struct {
	conn     *websocket.Conn
	send     chan []byte
	playerID string
}

type Message struct {
	Type    string      `json:"type"`
	Content interface{} `json:"content"`
}

const (
	MessageTypeBattleStart  = "battle_start"
	MessageTypeBattleResult = "battle_result"
)

type WebSocketHandler struct {
	connections sync.Map
	crossClient pb.CrossServiceClient
}

func NewWebSocketHandler(crossClient pb.CrossServiceClient) *WebSocketHandler {
	return &WebSocketHandler{
		crossClient: crossClient,
	}
}

func (h *WebSocketHandler) HandleWebSocket(w http.ResponseWriter, r *http.Request) {
	// 验证token
	token := r.URL.Query().Get("token")
	if token == "" {
		log.Println("Missing token")
		http.Error(w, "Unauthorized", http.StatusUnauthorized)
		return
	}

	// 解析token
	claims, err := utils.ParseToken(token)
	if err != nil {
		log.Printf("Invalid token: %v", err)
		http.Error(w, "Unauthorized", http.StatusUnauthorized)
		return
	}

	conn, err := upgrader.Upgrade(w, r, nil)
	if err != nil {
		log.Printf("Websocket upgrade failed: %v", err)
		return
	}

	// 创建新的连接
	c := &Connection{
		conn:     conn,
		send:     make(chan []byte, 256),
		playerID: fmt.Sprintf("%d", claims.UserID), // 转换为string
	}

	// 存储连接
	h.connections.Store(c.playerID, c)

	// 启动读写goroutines
	go h.readPump(c)
	go h.writePump(c)
}

func (h *WebSocketHandler) readPump(c *Connection) {
	defer func() {
		h.connections.Delete(c.playerID)
		c.conn.Close()
	}()

	for {
		_, message, err := c.conn.ReadMessage()
		if err != nil {
			if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway, websocket.CloseAbnormalClosure) {
				log.Printf("error: %v", err)
			}
			break
		}

		// 处理消息
		h.handleMessage(c, message)
	}
}

func (h *WebSocketHandler) writePump(c *Connection) {
	defer func() {
		c.conn.Close()
	}()

	for message := range c.send {
		err := c.conn.WriteMessage(websocket.TextMessage, message)
		if err != nil {
			log.Printf("Write message error: %v", err)
			return
		}
	}
	c.conn.WriteMessage(websocket.CloseMessage, []byte{})
}

func (h *WebSocketHandler) handleMessage(c *Connection, message []byte) {
	var msg Message
	if err := json.Unmarshal(message, &msg); err != nil {
		log.Printf("Error parsing message: %v", err)
		return
	}

	switch msg.Type {
	case "match_result":
		if content, ok := msg.Content.(map[string]interface{}); ok {
			if battleID, ok := content["battle_id"].(string); ok {
				h.sendBattleStart(c.playerID, battleID)
			}
		}
	}
}

// 发送战斗开始消息
func (h *WebSocketHandler) sendBattleStart(playerID string, battleID string) {
	msg := Message{
		Type: MessageTypeBattleStart,
		Content: map[string]string{
			"battle_id": battleID,
		},
	}

	if conn, ok := h.connections.Load(playerID); ok {
		if c, ok := conn.(*Connection); ok {
			data, _ := json.Marshal(msg)
			c.send <- data
		}
	}
}
